package fun.sssdnsy.media.image;

import javafx.scene.Node;
import org.fxmisc.richtext.model.Codec;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;

public interface LinkedImage {
    static Codec<LinkedImage> codec() {
        return new Codec<LinkedImage>() {
            @Override
            public String getName() {
                return "LinkedImage";
            }

            @Override
            public void encode(DataOutputStream os, LinkedImage image) throws IOException {
                if (image instanceof RealLinkedImage) {
                    // 类型标记：REAL
                    os.writeByte(ImageType.REAL.ordinal());
                    String path = ((RealLinkedImage) image).getImagePath().replace("\\", "/");
                    Codec.STRING_CODEC.encode(os, path);
                } else if (image instanceof EmbeddedLinkedImage) {
                    // 类型标记：EMBEDDED
                    os.writeByte(ImageType.EMBEDDED.ordinal());
                    byte[] data = ((EmbeddedLinkedImage) image).getImageData();
                    os.writeInt(data.length);
                    os.write(data);
                } else {
                    // 类型标记：EMPTY
                    os.writeByte(ImageType.EMPTY.ordinal());
                }
            }

            @Override
            public LinkedImage decode(DataInputStream is) throws IOException {
                ImageType ImageType = fun.sssdnsy.media.image.ImageType.values()[is.readByte()];
                switch (ImageType) {
                    case REAL:
                        String path = Codec.STRING_CODEC.decode(is);
                        return new RealLinkedImage(path);
                    case EMBEDDED:
                        int length = is.readInt();
                        byte[] data = new byte[length];
                        is.readFully(data);
                        return new EmbeddedLinkedImage(data);
                    default:
                        return new EmptyLinkedImage();
                }
            }
        };
    }

    boolean isReal();

    // 新增方法，仅 EmbeddedLinkedImage 需要实现
    default byte[] getImageData() {
        throw new UnsupportedOperationException();
    }

    // 原方法保留
    default String getImagePath() {
        throw new UnsupportedOperationException();
    }

    Node createNode();
}
